<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span
          style="
            display: inline-block;
            width: calc(100% - 51px);
            padding-right: 10px;
            text-align: right;
          "
        >
          <a-button
            @click="toggleScreen"
            icon="appstore"
            style="height: 20px; width: 20px; border: 0px"
          >
          </a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!--类型联动型号-->
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类型">
					<a-select placeholder="请选择" v-decorator.trim="[ 'typeId', validatorRules.notBlank]"
						@change="typeChange">
						<a-select-option :value="item.typeId" v-for="item in typeList" :key="item.typeId">
							{{item.typeDesc}}
						</a-select-option>
					</a-select>
				</a-form-item> -->
        <!-- 				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="型号">
					<a-select placeholder="请选择" v-decorator.trim="[ 'modelId', validatorRules.notBlank]"
						@change="modelChange">
						<a-select-option v-for="(item, index) in modelList" :key="index" :value="item.modelId">
							{{ item.name }}
						</a-select-option>
					</a-select>
				</a-form-item> -->
        <!-- <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="ID" v-decorator.trim="[ 'serverID', validatorRules.notBlank]" />
				</a-form-item> -->
        <!-- <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="类型" v-decorator.trim="[ 'serverType', validatorRules.notBlank]" />
				</a-form-item> -->
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="类型">
					<a-select placeholder="请选择" v-decorator.trim="[ 'typeId', validatorRules.notBlank]"
						@change="typeChange">
						<a-select-option :value="item.typeId" v-for="item in typeList" :key="item.typeId">
							{{item.typeDesc}}
						</a-select-option>
					</a-select>
				</a-form-item> -->
        <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="名称"
            :maxLength="30"
            v-decorator.trim="[
              'servername',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(
                    /[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,
                    ''
                  );
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          label="IP地址"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="IP地址"
            :maxLength="20"
            v-decorator.trim="[
              'serverIP',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9.]/g, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="端口" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="端口"
            :maxLength="20"
            v-decorator.trim="[
              'serverPort',
              {
                rules: validatorRules.notBlank.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^0-9]/g, '');
                },
              },
            ]"
          />
        </a-form-item>
        <a-form-item label="密钥" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="密钥"
            :maxLength="30"
            v-decorator.trim="['secret', validatorRules.notBlank]"
          />
        </a-form-item>
        <a-form-item label="启用" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-decorator.trim="['used', validatorRules.notBlank]">
            <a-radio value="1">是</a-radio>
            <a-radio value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="描述" v-decorator.trim="[ 'devDesc', validatorRules.notBlank]" />
				</a-form-item> -->
        <!-- <a-form-item label="地点" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="地点" v-decorator.trim="[ 'location', validatorRules.notBlank]" />
				</a-form-item>
				<a-form-item label="启用" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-radio-group v-decorator.trim="[ 'used', validatorRules.notBlank]">
						<a-radio value="1">是</a-radio>
						<a-radio value="0">否</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item label="时间同步" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-select placeholder="请选择" v-decorator.trim="[ 'timeSync', validatorRules.notBlank]">
						<a-select-option value="1">是</a-select-option>
						<a-select-option value="0">否</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="NTP服务地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input :disabled="!(form.getFieldValue('timeSync') === '1')" placeholder="NTP服务地址" v-decorator.trim="[ 'ntpAddr']" />
				</a-form-item>
				<a-form-item label="NTP服务端口" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input :disabled="!(form.getFieldValue('timeSync') === '1')" placeholder="NTP服务端口" v-decorator.trim="[ 'ntpPort']" />
				</a-form-item>
				<a-form-item label="端口" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="端口" v-decorator.trim="[ 'port', validatorRules.isNumber]" />
				</a-form-item>
				<a-form-item label="控制协议" :labelCol="labelCol" :wrapperCol="wrapperCol"> -->
        <!-- 在对应的协议组中选择 -->
        <!-- 	<a-select placeholder="请选择" v-decorator.trim="[ 'ctrlProtocol', validatorRules.notBlank]">
						<a-select-option v-for="item in ctrlProtocolList" :key="item" :value="item">
							{{item}}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="访问用户名" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="访问用户名" v-decorator.trim="[ 'userName', validatorRules.notBlank]" />
				</a-form-item>
				<a-form-item label="访问密码" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-input placeholder="访问密码" v-decorator.trim="[ 'userPassword', validatorRules.notBlank]" />
				</a-form-item> -->
      </a-form>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
      >
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>

      <a-button @click="handleNext" type="primary" :loading="confirmLoading"
        >下一步</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import pick from "lodash.pick";
import { getAction, postAction } from "@/api/manage";
export default {
  name: "MediaAddModal",
  components: {},
  data() {
    return {
      typeList: [],
      modelList: [],
      ctrlProtocolList: [],
      model: {},
      servertype: 0,
      form: this.$form.createForm(this),
      validatorRules: {
        notBlank: {
          rules: [
            {
              required: true,
              message: "请输入必填项!",
            },
          ],
        },
        isNumber: {
          rules: [
            {
              required: true,
              pattern: /^[1-9]\d*$/,
              message: "请输入数字类型!",
            },
          ],
        },
      },
      title: "新增",
      visible: false,
      modaltoggleFlag: true,
      confirmDirty: false,
      disableSubmit: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      modalWidth: 800,
      drawerWidth: 700,
      confirmLoading: false,
    };
  },
  created() {
    //初始化默认值
    this.form.getFieldDecorator("used", {
      initialValue: "1",
    });
    this.form.getFieldDecorator("timeSync", {
      initialValue: "1",
    });
    this.form.getFieldDecorator("ntpPort", {
      initialValue: "123",
    });
  },
  computed: {},
  methods: {
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    show() {
      //显示弹层
      this.visible = true;
      // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
      this.resetScreenSize();
      this.form.resetFields();
      // this.$nextTick(() => {
      // 	this.form.setFieldsValue(pick(this.model,
      // 		'typeId', 'modelId', 'name', 'devDesc', 'location',
      // 		'used', 'timeSync', 'ntpAddr', 'ntpPort', 'ip',
      // 		'port', 'ctrlProtocol', 'userName', 'userPassword'
      // 		))
      // });
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            "servername",
            "serverIP",
            "secret",
            "serverPort",
            "used",
            "id"
          )
        );
      });
    },
    typeChange(value) {
      //类型联动型号
      //清空类型
      this.modelList = [];
      this.form.setFieldsValue({ modelId: undefined });
      //联动查询
      getAction("/dev/model/getbytype?typeId=" + value).then((res) => {
        if (res.code == "00000") {
          this.modelList = res.data;
        } else {
          this.$message.warning("获取型号错误");
        }
      });
    },
    modelChange(value) {
      //改变型号，默认协议改变
      let selectModel;
      this.modelList.some((item, i) => {
        if (value === item.modelId) {
          selectModel = item;
          return true;
        }
      });

      console.log(">>>>>>设备型号：" + JSON.stringify(selectModel));

      if (selectModel === undefined) {
        this.$message.warning("获取型号错误");
        return;
      }

      try {
        this.ctrlProtocolList = selectModel.ctrlProtocolGroup.split(";");
        this.form.getFieldDecorator("ctrlProtocol", {
          initialValue: selectModel.defaultCtrlProtocol,
        });
      } catch (e) {
        //TODO handle the exception
        console.log("获取控制协议组失败！");
      }
    },
    close() {
      this.$emit("close");
      this.visible = false;
      this.disableSubmit = false;
    },
    handleNext() {
      //添加设备下一步
      const that = this;
      this.confirmLoading = [];
      // this.
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          // this.$set(this.formData,'servertype',0);
          let formData = Object.assign(this.model, values);
          formData["serverType"] = 0;
          // const formDatas = formData.push({'servertype':"0"})
          // console.log(this.model,'111')
          // console.log(this.value,'022')
          console.log(formData, "3333");
          postAction("/serve/addserve", formData)
            .then((res) => {
              if (res.code == "00000") {
                //子类绑定父类引组件的方法
                that.$emit("ok");
                that.$message.success("媒体服务添加成功");
                //跳转新tab
                that.$router.push({
                  name: "/ser/media",
                  params: {
                    devId: res.data,
                  },
                });
              } else {
                that.$message.warning("操作失败" + res.msg);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        }
      });
    },
    handleCancel() {
      this.close();
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
  },
};
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>
